import React, { useEffect, useRef, useState } from "react";
import { Space, Button, Modal, Toast, Avatar } from "antd-mobile"
import {
  API,
  REDIRECT_COVER,
  REDIRECT_TITLE,
  BASE_PATH,
} from "@/config";
import { useRouter } from "next/router";
import { appNavigate, appTypeCheck, checkENV, checkENV2, navigateTo } from "@/utils";
import requewt from "@/utils/requewt";
import callFeedback from "@/components/common/modalFeedback";
import { GiftComp, PrizeComp, RuleComp, StuffComp } from "@/components/common";
import { usePathname } from "next/navigation";
import Cookies from "universal-cookie";
import { useSession } from "next-auth/react";
import { useCommonHandler } from "../hooks";
const pageName = "toolbar";
const klassName = pageName.replace(/\./g, '-');

export default function Toolbar({ user }) {
  const [visible, setVisible] = useState(undefined);
  const [loading, setLoading] = useState(undefined);
  const [env, setENV] = useState(undefined);
  const phoneAndAddress = useRef()
  const router = useRouter();
  const pathname = usePathname();
  const { handleShare } = useCommonHandler()
  let flag = 0;
  useEffect(() => {
    (async () => {
      const cookie = new Cookies('auth')
      const seen = sessionStorage.getItem(`seen`);
      if (!seen && cookie.get('auth')) {
        compHandler.rule();
        sessionStorage.setItem(`seen`, `1`)
      }
    })()
  }, [])
  const onInfoChange = (value) => {
    phoneAndAddress.current = value

  }
  // useEffect(() => {
  //   if (env !== `mini`) return;
  //   // 处理小程序通讯的分享
  //   const data = {
  //     title: REDIRECT_TITLE, // 分享标题
  //     path: REDIRECT_WX_URL,
  //     imageUrl: REDIRECT_WX_COVER
  //   }
  //   wx.miniProgram.postMessage({data})
  // }, [env])

  /**
   * 等待环境加载
   * @param ev
   */
  const waitForAuth = (ev) => {
    if (flag >= 30) {
      // Toast.show({duration: 1000, content: `持续授权失败！请保证网络畅通、并在引力域的APP或小程序中打开`, position: `top`});
      return
    }
    setTimeout(() => {
      if (ev) {
        setENV(ev);
        return;
      }
      flag++;
      const resolve = checkENV();
      waitForAuth(resolve);
    }, 100);
  };

  const compHandler = {
    link: async (url) => {
      const env = await checkENV2();
      if (env === `mini`) {
        wx?.miniProgram.navigateTo({ url: `/pages/subscribe/subscribe?id=17` })
      } else if (env === `app`) {
        const { type, value } = appTypeCheck(`https://head.uni.changan.com.cn/order/#/orderUNI/subscribe?id=19`) || {};
        appNavigate(type, value);
      }
    },
    navigate: url => navigateTo(url),
    // 打开规则
    rule: () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal rule-modal close-at-center-bottom`,
        title: <div>活动规则</div>,
        content: <div className="inner"><RuleComp /></div>,
        actions: [],
        closeOnAction: true,
        closeOnMaskClick: true,

      })
    },
    // 我的奖品
    prize: async () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal rule-modal close-at-center-bottom`,
        content: <div className="inner"><PrizeComp onInfoChange={onInfoChange} /></div>,
        title: <div>我的奖品</div>,
        actions: [],
        // hideClose:true,
        closeOnAction: true,
        closeOnMaskClick: true,
        onClose: () => {
          requewt(API.user.userPhoneAndAddress, { body: { ...phoneAndAddress.current }, method: 'post', headers: { "Content-Type": "multipart/form-data" }, }).then(({ error_code, msg }) => {
            // console.log('xxxxx')
            if (error_code !== 0) {
              // Toast.show({
              //   content: '操作成功',

              // })
              return Toast.show({
                content: <div dangerouslySetInnerHTML={{ __html: msg || '操作失败' }}></div>,
              })
            }

            // return Toast.show({
            //   content: '操作成功',

            // })
          })
        }
      })
    },
    // 点击分享
    pressShare: () => {
      // 记录分享
      if (env === `app`) {
        //
        const json = {
          shareTitle: REDIRECT_TITLE,
          // shareUrl: REDIRECT_URL,
          shareUrl: `https://head.uni.changan.com.cn/quanzi/#/zixunPreview?artId=1959`,
          shareImg: REDIRECT_COVER,
          shareDesc: `解码有惊喜，大额积分等你来拿！`,
          shareType: "3",
          isImg: "0",

          // isMiniProgram: "1",
          // userName: MINI_P_ID,
          // path: MINI_P_PATH,
          // miniprogramType: 0,
        }
        try {
          // 菜单分享
          window.UNIApp?.shareTo(JSON.stringify(json), 'shareCallBack')
        } catch (error) {
          Toast.show({ content: `分享失败` })
        }

      }
      // 小程序分享
      else if (env === `mini`) {
        callFeedback({
          title: <div dangerouslySetInnerHTML={{ __html: `请点击右上角「...」进行分享` }}>
          </div>
        })
      } else {
        callFeedback({
          bodyClassName: 'share-tips-modal',
          actions: [],
          hideClose: true,
          title: <div >
          </div>,
          content: <img src={`${BASE_PATH}/img/game/share_indication.png`} width='308' />
        })
      }
      setTimeout(() => {
        requewt(API.user.share)
      }, 3000)
    },
    close: () => {
      setVisible(undefined)
    },
    stuff: () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        content: <div className="inner"><StuffComp /></div>,
        actions: [],
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    }
  }


  return (
    <div className={`cp-${klassName}`}>
      <div className="inner">
        {/*{*/}
        {/*  [`/rank`, `/tool`].includes(pathname) &&*/}
        {/*  <Button className="back-btn" onClick={e => Router.back()} fill="none">*/}
        {/*    <LeftOutline color="#333" />*/}
        {/*  </Button>*/}
        {/*}*/}

        <Space direction="vertical" size={[20, 20]} className="btn-group">
          <div key={1} className="side-btn" onClick={compHandler.rule}>
            活<br />动<br />规<br />则
          </div>

          <div key={2} className="side-btn" onClick={e => compHandler.prize()}>
            我<br />的<br />奖<br />品
          </div>
          <div key={3} className="side-btn" onClick={e => handleShare()}>
            邀<br />请<br />好<br />友
          </div>


        </Space>

      </div>

    </div>
  )
}